<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Model;
class ProductController extends Controller {
    public function _initialize(){
        if(!isset($_SESSION['admin'])) {
            $this->display('Index/login');
            exit;
        }
    }
    
    public function productClassDetail(){
        $this->display('Product/product-class-detail');
    }

    public function saveProductClass(){
    	$this->display('Product/product-class-list');
    }

    public function productClassList(){
    	$this->display('Product/product-class-list');
    }

    public function productTemplateList(){
		$this->display('Product/product-template-list');
    }

    public function productTemplateDetail(){
		$this->display('Product/product-template-detail');
    }

    public function productList(){
		$this->display('Product/product-list');
    }

    public function productDetail(){
		$this->display('Product/product-detail');
    }

    public function productCommentList(){
		$this->display('Product/product-comment-list');
    }

    public function productDiscountList(){
    	$this->display('Product/product-discount-list');
    }

    public function productDiscountAdd(){
    	$this->display('Product/product-discount-add');
    }

    public function productShoppingActivity(){
        $Model = M('shopping_cart_activity');
        $r = $Model->find();
        $this->assign('status', $r['status']);
        $this->assign('content', $r['content']);
    	$this->display('Product/product-shopping-cart-activity');
    }

    public function updateProductShoppingActivity(){
        $data = I('param.');
        $Model = M('shopping_cart_activity');
        $param['shopping_cart_activity_id'] = '1';
        if($Model->where($param)->find()){
            $r = $Model->where($param)->save($data);
        }else{
            $r = $Model->where($param)->add($data);
        }
        
        echo json_encode($r);
    }

    public function getProductClassTree(){
        $Model = M('product_class');
        $r['data'] = $Model->order('product_class.index desc')->select();
        echo json_encode($r);
    }

    public function getProductClass(){
        $param['product_class_id'] = I('param.product_class_id', '');

        $Model = new Model();
        if($param['product_class_id'] == ''){
            //仓库管理员不能看到商品分类
            $r['data'] = '';
            if(session('admin')['type'] != '0'){
                $r['data'] = $Model->order('product_class.index desc')->table('product_class')->select();
            }

            //遍历product_class,找出每种product所对应的id和pid
            foreach ($r['data'] as &$data) {
                if($data['type'] == '1'){
                    $data['id'] = $data['product_class_id'];
                    //$data['open'] = true;
                    $amount = $Model
                        ->field('count(*) as amount')
                        ->table('product_template')
                        ->join('product on product.product_template_id=product_template.product_template_id')
                        ->where('product_template.class1 = "%s"', $data['product_class_id'])
                        ->find();
                    $data['amount'] = $amount['amount'];
                }else if($data['type'] == '2'){
                    $data['id'] = $data['parent_id'].'-'.$data['product_class_id'];
                    //$data['open'] = true;
                    $amount = $Model
                        ->field('count(*) as amount')
                        ->table('product_template')
                        ->join('product on product.product_template_id=product_template.product_template_id')
                        ->where('product_template.class2 = "%s"', $data['product_class_id'])
                        ->find();
                    $data['amount'] = $amount['amount'];
                }else if($data['type'] == '3'){
                    $id = $Model->table('product_class')->where('product_class_id="%s"', $data['parent_id'])->find();
                    $data['id'] = $id['parent_id'].'-'.$data['parent_id'].'-'.$data['product_class_id'];
                    $amount = $Model
                        ->field('count(*) as amount')
                        ->table('product_template')
                        ->join('product on product.product_template_id=product_template.product_template_id')
                        ->where('product_template.class3 = "%s"', $data['product_class_id'])
                        ->find();
                    $data['amount'] = $amount['amount'];
                }
                
            }
        }else{
            $r = $Model->table('product_class')->where($param)->find();
            if($r['type'] == '1'){
                $r['id'] = $r['product_class_id'];
            }else if($r['type'] == '2'){
                $r['id'] = $r['parent_id'].'-'.$r['product_class_id'];
            }else if($r['type'] == '3'){
                $id = $Model->table('product_class')->where('product_class_id="%s"', $r['parent_id'])->find();
                $r['id'] = $id['parent_id'].'-'.$r['parent_id'].'-'.$r['product_class_id'];
            }
        }

        echo json_encode($r);
    }

    public function updateProductClass(){
        $data = I('param.');
            
        $Model = M('product_class');
        
        if($data['product_class_id'] != ''){
            $r = $Model->find($data['product_class_id']);
            if($r['imgurl'] != $data['imgurl']){
                unlink(DOC_ROOT . '/../' . $r['imgurl']);
            }
            $r = $Model->save($data);
        }else{
            $r = $Model->add($data);
        }
        echo json_encode($r);
    }

    //先删除图片，再删除记录
    public function deleteProductClass(){
        $param['product_class_id'] = I('param.product_class_id', '');
        $Model = M('product_class');
        $r = $Model->find($param['product_class_id']);
        unlink(DOC_ROOT . '/../' . $r['imgurl']);
        $r = $Model->where($param)->delete();
        echo json_encode($r);
    }

    public function getProductTemplate(){
        $param['product_template_id'] = I('param.product_template_id', '');

        $ProductTemplate = D('ProductTemplate');
        if($param['product_template_id'] == ''){
            //仓库管理员不能看见商品模板
            $r['data'] = '';
            if(session('admin')['type'] != '0'){
                $r['data'] = $ProductTemplate->select();
            }
        }else{
            
            $r = $ProductTemplate->relation(true)->where($param)->find();
        }

        echo json_encode($r);
    }

    //管理员点击保存商品模板
    public function updateProductTemplate(){
        $data = I('param.');
        $data['imgurl1'] = $data['imgurl'][0];
        $data['imgurl2'] = $data['imgurl'][1];
        $data['imgurl3'] = $data['imgurl'][2];
        $data['smimgurl'] = $data['smimgurl'];
        
        $data['product_detail'] = htmlspecialchars_decode($data['product_detail']);

        $product_template = M('product_template');
        if($data['product_template_id'] != ''){
            $r1 = $product_template->find($data['product_template_id']);
            $arr1 = array($r1['imgurl1'], $r1['imgurl2'], $r1['imgurl3']);
            $arr2 = array($data['imgurl1'], $data['imgurl2'], $data['imgurl3']);
            $arr = array_diff($arr1, $arr2);
            foreach ($arr as &$url) {
                unlink(DOC_ROOT . '/../' . $url);
            }
            $r1 = $product_template->save($data);
        }else{
            $r1 = $product_template->add($data);
            $data['product_template_id'] = $r1;
        }

        $product = M('product');
        //对于每个A仓库，执行不重复地添加商品操作
        unset($param);
        $a_repository_ids = $data['a_repository_id'];
        $b_repository_ids = $data['b_repository_id'];
        unset($data['a_repository_id']);
        unset($data['b_repository_id']);

        foreach ($a_repository_ids as $key => $a_repository_id) {
            $param['product_template_id'] = $data['product_template_id'];
            $param['a_repository_id'] = $a_repository_id;
            $p = $product->where($param)->select();
            if(count($p) == 0){
                $data['remain_amount'] = $data['origin_amount'];
                $data['a_repository_id'] = $a_repository_id;
                $r2 = $product->add($data);
            }
        }

        //对于每个B仓库，执行不重复地添加商品操作
        unset($param);
        unset($data['a_repository_id']);
        unset($data['b_repository_id']);
        foreach ($b_repository_ids as $key => $b_repository_id) {
            $param['product_template_id'] = $data['product_template_id'];
            $param['b_repository_id'] = $b_repository_id;
            $p = $product->where($param)->select();
            if(count($p) == 0){
                $data['remain_amount'] = $data['origin_amount'];
                $data['b_repository_id'] = $b_repository_id;
                $r2 = $product->add($data);
            }
        }

        echo json_encode($r1);
    }

    //管理员点击保存并更新仓库商品价格
    public function updateProductTemplatePrice(){
        $data = I('param.');
        $data['imgurl1'] = $data['imgurl'][0];
        $data['imgurl2'] = $data['imgurl'][1];
        $data['imgurl3'] = $data['imgurl'][2];
        $data['smimgurl'] = $data['smimgurl'];
        $data['product_detail'] = htmlspecialchars_decode($data['product_detail']);

        $product_template = M('product_template');
        $r1 = $product_template->find($data['product_template_id']);

        $arr1 = array($r1['imgurl1'], $r1['imgurl2'], $r1['imgurl3']);
        $arr2 = array($data['imgurl1'], $data['imgurl2'], $data['imgurl3']);
        $arr = array_diff($arr1, $arr2);
        foreach ($arr as &$url) {
            unlink(DOC_ROOT . '/../' . $url);
        }

        $r1 = $product_template->save($data);

        $product = M('product');
        //对于每个A仓库，执行更新商品操作
        unset($param);
        $a_repository_ids = $data['a_repository_id'];
        $b_repository_ids = $data['b_repository_id'];
        unset($data['a_repository_id']);
        unset($data['b_repository_id']);
        foreach ($a_repository_ids as $key => $a_repository_id) {
            $param['product_template_id'] = $data['product_template_id'];
            $param['a_repository_id'] = $a_repository_id;
            $r2 = $product->where($param)->save($data);
        }

        //对于每个B仓库，执行更新商品操作
        unset($param);
        unset($data['a_repository_id']);
        unset($data['b_repository_id']);
        foreach ($b_repository_ids as $key => $b_repository_id) {
            $param['product_template_id'] = $data['product_template_id'];
            $param['b_repository_id'] = $b_repository_id;
            $r2 = $product->where($param)->save($data);
        }

        echo json_encode($r1);
    }

    public function updateProductStatus(){
        $param['product_template_id'] = I('param.product_template_id');
        $data['status'] = I('param.status');

        $ProductTemplate = M('product_template');
        $r = $ProductTemplate->where($param)->save($data);

        $Product = M('product');
        $r = $Product->where($param)->save($data);
        echo json_encode($r);
    }

    public function getProduct(){
        $product_id = I('param.product_id', '');

        $Product = D('Product');
        if($product_id == ''){
            //仓库管理员只可以看到自己所属的仓库的商品列表
            if(session('admin')['a_repository_id'] != null && session('admin')['a_repository_id'] != '0'){
                $param['a_repository_id'] = session('admin')['a_repository_id'];
            }else if(session('admin')['b_repository_id'] != null && session('admin')['b_repository_id'] != '0'){
                $param['b_repository_id'] = session('admin')['b_repository_id'];
            }
            $r['data'] = $Product->where($param)->relation('product_template')->select();
        }else{
            $param['product_id'] = $product_id;
            $r = $Product->where($param)->find();
        }

        echo json_encode($r);
    }

    public function updateProduct(){
        $data = I('param.');

        $Model = M('Product');
        if($data['product_id'] != ''){
            $r = $Model->save($data);
        }
        echo json_encode($r);
    }

    //管理员补足库存
    public function addAdminRepository(){
        $data = I('param.');

        if($data['a_repository_id'] == ''){
            $repository = 'b_repository_id';
            $param['b_repository_id'] = $data['b_repository_id'];
        }else{
            $repository = 'a_repository_id';
            $param['a_repository_id'] = $data['a_repository_id'];
        }

        $product = D('Product');
        $r = $product->where($param)->relation('product_template')->select();
        //对于每个商品，将剩余库存量改成原始库存量
        $RepositoryAdmin = M('admin_repository');
        foreach ($r as &$pro) {
            //更新product表
            $p['product_id'] = $pro['product_id'];
            $p['default_amount'] = $pro['origin_amount'];
            $r1 = $product->save($p);

            //插入repository_admin表
            $pro['add_amount'] = $pro['origin_amount'] - $pro['default_amount'];
            $pro['remain_amount'] = $pro['origin_amount'];
            if($pro['add_amount'] > 0){
                $pro['note'] = $data['note'];
                $pro['barcode'] = $pro['product_template']['barcode'];
                $r2 = $RepositoryAdmin->add($pro);
            }  
        }
        echo json_encode($r);
    }

    public function getProductDiscount(){
        $param['product_discount_id'] = I('param.product_discount_id', '');

        $Model = D('product_discount');
        if($param['product_discount_id'] == ''){
            $r['data'] = $Model
                ->join('product on product_discount.product_id = product.product_id')
                ->join('product_template on product.product_template_id = product_template.product_template_id')
                ->field('product_discount.*, product.a_repository_id, product.b_repository_id, product.kj_price, product.name, product_template.barcode, product_template.class1, product_template.class2, product_template.class3, product_template.key')
                ->select();
        }else{
            
            $r = $Model
                ->join('product on product_discount.product_id = product.product_id')
                ->join('left join a_repository on product.a_repository_id = a_repository.a_repository_id')
                ->join('left join b_repository on product.b_repository_id = b_repository.b_repository_id')
                ->join('product_template on product.product_template_id = product_template.product_template_id')
                ->where($param)
                ->field('product_discount.*, product.a_repository_id, product.b_repository_id, product.kj_price, product.name, product_template.barcode, a_repository.name as a_repository_name, b_repository.name as b_repository_name')
                ->find();
        }

        echo json_encode($r);
    }

    public function updateProductDiscount(){
        $data = I('param.');
        $data['remain_amount'] = $data['cx_amount'];
        $Model = M('product_discount');
        $Model->startTrans();
        $r = true;
        if(!empty($data['product_ids'])){
            foreach ($data['product_ids'] as &$value) {
                $data['product_id'] = $value;
                $r = $Model->add($data);
                if(!$r){
                    break;
                }
            }
        }else{
            $r = $Model->save($data);
        }
        
        if($r){
            $Model->commit();
        }else{
            $Model->rollback();
        }

        echo json_encode($r);
    }

    public function deleteProductDiscount(){
        $param['product_discount_id'] = I('param.product_discount_id');
        $Model = M('product_discount');
        $r = $Model->where($param)->delete();
        echo json_encode($r);
    }

    public function getProductComment(){
        $param['product_comment_id'] = I('param.product_comment_id', '');

        $Model = D('ProductComment');
        if($param['product_comment_id'] == ''){
            $r['data'] = '';
            //仓库管理员不能看到用户评论
            if(session('admin')['type'] != '0'){
                $r['data'] = $Model->relation(true)->select();
            }
        }else{
            $r = $Model->relation(true)->where($param)->find();
        }
        echo json_encode($r);
    }

    public function updateProductComment(){
        $data = I('param.');
        $Model = M('product_comment');
        $Model->startTrans();
        $r = true;
        if(!empty($data['product_comment_ids'])){
            foreach ($data['product_comment_ids'] as &$value) {
                $param['product_comment_id'] = $value;
                if($data['status'] == '2'){
                    $r = $Model->where($param)->delete();
                }else{
                    $r = $Model->where($param)->save($data);
                }
                if(!$r){
                    break;
                }
            }
        }else{
            $r = $Model->save($data);
        }
        
        if($r){
            $Model->commit();
        }else{
            $Model->rollback();
        }

        echo json_encode($r);
    }

    public function deleteProductComment(){
        $param['product_comment_id'] = I('param.product_comment_id');
        $Model = M('ProductComment');
        $r = $Model->where($param)->delete();
        echo json_encode($r);
    }

    //文件上传
    public function upload(){
        saveFile('product');
    }

    //商品分类上传
    public function uploadProductClass(){
        saveFile('product_class');
    }
}